package com.gopay.bis.ipay.ebank.operation;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.ipay.ebank.util.PlainTextUtil;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.ipay.ebank.IpayMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.HttpTransport;
import com.gopay.remote.bank.ICertHelper;

/**
 * 民生i支付交易查询
 * 
 * @IpayQuery.java
 * @author zhengxue
 * @2016-7-28 上午11:02:45 www.gopay.com.cn Inc.All rights reserved.
 */
public class IpayQuery {
    // 签名验签处理类
    private ICertHelper ipayCertHelper;

    protected Logger log = LoggerFactory.getLogger(IpayQuery.class);

    public Object queryOrder(IpayMessage message) throws GopayException {
        try {
            String signMessage = (String) ipayCertHelper.sign(message);
            Map<String, String> refundReq = new HashMap<String, String>();
            refundReq.put("oid_partner", message.getOidPartner());
            refundReq.put("no_order", message.getNoOrder());
            refundReq.put("dt_order", message.getDtOrder());
            refundReq.put("ori_no_order", message.getOriNoOrder());
            refundReq.put("sign", signMessage);
            log.error("IpayQuery req: " + refundReq);
            // 通讯类
            HttpTransport httpTransport = new HttpTransport();
            httpTransport.setUrl(message.getQueryUrl());
            Object obj = (Object) httpTransport.submit(refundReq);
            log.error("IpayQuery res: " + obj);
            // 解析查询结果
            return parseQueryOrderRes(obj, message);
        } catch (Exception e) {
            BankLogUtils.printB2CQueryExceptionLog(message, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6037);
        }
    }

    /**
     * 查询结果解析
     * 
     * @param object
     * @return
     * @throws GopayException
     */
    public IpayMessage parseQueryOrderRes(Object object, IpayMessage queryMessage) throws GopayException {
        try {
            HashMap<String, String> data = new HashMap<String, String>();
            // 将json字符串转换成jsonObject
            JSONObject jsonObject = JSONObject.fromObject((String)object);
            log.error("IpayQuery res jsonObject: " + jsonObject);
            queryMessage.setPlainMessage(PlainTextUtil.getPlainText(jsonObject));
            queryMessage.setSignMessage(jsonObject.getString("sign"));
            boolean flag = (Boolean) ipayCertHelper.verify(queryMessage);
            queryMessage.setFlag(flag); // 验签结果

            if (flag) {
                queryMessage.setMoneyOrder(jsonObject.getString("money_order"));
                queryMessage.setNoOrder(jsonObject.getString("no_order"));
                queryMessage.setOriNoOrder(jsonObject.getString("ori_no_order"));
                queryMessage.setRespCode(jsonObject.getString("resp_code"));
                queryMessage.setRespMsg(jsonObject.getString("resp_msg"));
                queryMessage.setRespType(jsonObject.getString("resp_type"));
                queryMessage.setOriRespType(jsonObject.getString("ori_resp_type"));
                queryMessage.setOriRespCode(jsonObject.getString("ori_resp_code"));
                queryMessage.setOriRespMsg(jsonObject.getString("ori_resp_msg"));
            }
            log.error("IpayQuery parse return: " + ToStringBuilder.reflectionToString(queryMessage));
            return queryMessage;
        } catch (Exception e) {
            BankLogUtils.printB2CQueryExceptionLog(queryMessage, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6039);
        }
    }

    /**
     * 生成待签名串
     * 
     * @param paramMap
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getPlainText(Map<String, String> params) throws UnsupportedEncodingException {
        StringBuffer content = new StringBuffer();
        // 按照key做首字母升序排列
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
        for (int i = 0; i < keys.size(); i++) {
            String key = (String) keys.get(i);
            if ("sign".equals(key)) {
                continue;
            }
            String value = params.get(key);
            // 空串不参与签名
            if (isnull(value)) {
                continue;
            }
            content.append((i == 0 ? "" : "&") + key + "=" + value);

        }
        String signSrc = content.toString();
        if (signSrc.startsWith("&")) {
            signSrc = signSrc.replaceFirst("&", "");
        }
        return signSrc;
    }

    /**
     * str空判断
     * 
     * @param str
     * @return
     */
    public static boolean isnull(String str) {
        if (null == str || str.equalsIgnoreCase("null") || str.trim().equals("")) {
            return true;
        } else
            return false;
    }

    public void setIpayCertHelper(ICertHelper ipayCertHelper) {
        this.ipayCertHelper = ipayCertHelper;
    }

}
